﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApi333.Data;

namespace WebApi333.Domain
{
    public class EfRespository<T> : Irespository<T> where T : BaseEntity
    {
        private readonly Admin2222DbContext db;

        private DbSet<T> _entity;

        private DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }

        private IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        IQueryable<T> Irespository<T>.Table => throw new NotImplementedException();

        public void Delete(T entity)
        {
            Entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
